var operation = {
    'el':'',
    'init':function () {
        this.el = new Html({
            'appendLine':this.appendLine
        });
        this.addAttr();
        this.saveAttrValue();
        this.display();
    },
    //保存属性名
    'addAttr': function () {
        $('.add-attr').on('click',function () {
            layer.open({
                type: 1,
                title: false,
                area: ['450px', '150px'],
                shade: 0.6,//遮罩透明度
                closeBtn: 0,
                shadeClose: true,
                skin: 'yourclass',
                content: $('.add-attr-warpper'),
            });
            $('.cancel').off('click').on('click',function () {
                layer.closeAll();
            });
            
            $('.do').off('click').on('click',function () {
                var name = $.trim($('[name=attr_name]').val());
                if(!name){
                    layer.msg('请输入规格名称.');
                    return false;
                }

                if($('.size-warpper').find('.label').length >= 3){
                    layer.msg('最多只支持3个');
                    return false;
                }
                var attr_group=[];
                $('.size-warpper').find('.label').each(function(i){
                    var attrName=$('.size-warpper').find('.label').eq(i).text();
                    attr_group.push(attrName)
                })
                if(attr_group.indexOf(name)==-1){
                    $.ajax({
                        'type':'POST',
                        'url':'/attribute/add-attribute',
                        'data':{
                            name:name
                        },
                        'dataType':'json',
                        'success':function(data){
                            layer.closeAll();
                            if(data.code != 200){
                                layer.alert(data.msg);
                                return false;
                            }
    
                            var row = data.data.row;
                            var list = data.data.list;
                            $('.size-warpper').append([
                                '<div data-id="',row.id,'" data-class="label label-info" class="label label-info del-attr">',row.attribute_name,'<i class="cha icon-remove"></i></div>'
                            ].join(''));
    
                            //页面样式渲染
                            operation.gen(row,list);
                            $('[name=attr_name]').val('');
                        }
                    });
                }else{
                    layer.msg('已存在相同属性名')
                }
            });
        });
    },
    //删除属性名
    'deleteAttr':function(){
        $('.cha').off('click').on('click',function(){
            var that=this;
            layer.confirm('是否删除？', {
                btn: ['确定','取消'] //按钮
            }, function(){
                var attr_id = $(that).parent().attr('data-id'),
                flag = false;
                $(that).parent().remove();
                if($('.tab_'+attr_id).hasClass('active')){
                    flag = true;
                }
                $('.tab_'+attr_id).remove();
                $('#tab_'+attr_id).remove();
                if(flag){
                    var class_name = $('.attribute-name').find('li:last-child').attr('class');
                    $('.attribute-name').find('li:last-child').addClass('active');
                    $('#' + class_name).addClass('active');
                }
                layer.closeAll();                
            }, function(){
                layer.closeAll();
            });
            
        })
    },
    //保存属性值
    'saveAttrValue':function () {
        $('.save-attr-value').off('click').on('click',function(){
            var tr  = $(this).parents('tr');
            var attr_value = tr.find('[name=attr-value]').val();
            var attr_name = tr.find('[name=attr-name]').val();

            var id = tr.find('[name=id]').val();
            if(!attr_value){
                layer.msg('请输入规格值.');
                return false;
            }
            if(!id){
                layer.msg('非法输入.');
                return false;
            }
            if(!attr_name){
                layer.msg('非法输入.');
                return false;
            }

            $.ajax({
                'type':'POST',
                'url':'/attribute/add-attr-data',
                'data':{
                    id:id,
                    name:attr_name,
                    value:attr_value
                },
                'dataType':'json',
                'success':function(data)
                {
                    layer.closeAll();
                    if(data.code != 200)
                    {
                        layer.alert(data.msg);
                        return false;
                    }
                    //重新渲染整个tr
                    var row = data.data;
                    var index = (tr.prev().length) ? parseInt(tr.prev().find('td').eq(0).text())+1:1 ;
                    tr.html([
                        '    <td>',index,'</td>',
                        '    <td>',row.attr_name,'</td>',
                        '    <td>',row.value,'</td>',
                        '    <td>',
                        '        <span class="label label-warning deltr">删除</span>',
                        '    </td>'].join(''));
                    tr.attr('data-id',row.id);
                    tr.attr('data-attr-name',row.attr_name);
                    tr.attr('data-attr-value',row.value);
                }
            });

        });

        // 统一保存.
        // operation.gen();
    },
    //删除属性值
    'deleteAttrValue':function(){
        $('.deltr').off('click').on('click',function () {
            var tbody = $(this).parents('tbody');
            $(this).parents('tr').remove();
            var trs = tbody.find('tr');
            if(trs.length > 0){
                for (var i=0,len = trs.length;i<len;i++){
                    $(trs[i]).find('td:first').text(parseInt(i)+1);
                }
            }
        });

    },
    'display':function () {
        $('.display').off('click').on('click',function () {
            operation.el.display();
            $(".no_b").each(function(i){
                if(!$(".no_b").eq(i).val()){
                    $(this).css('border','1px solid rgb(255,65,65)')
                }
            }).on('blur',function(){
                var val=$(this).val();
                if(!$(this).val()){
                    $(this).css('border','1px solid rgb(255,65,65)')
                }else{
                    $(this).css('border','none')                    
                }
            })
        });
    },
    'gen':function (row,list) {
        var id = 'tab_' + row.id;
        operation.el.showNav(id,row);
        operation.el.showTab(id,list);
        operation.deleteAttrValue();
        operation.deleteAttr();
        // operation.el.display();
    },
    'appendLine':function () {
        $('.addtr').off('click').on('click',function () {
            var table = $(this).parents('table').find('tbody');
            var id = $(this).parents('.tab-pane').attr('id');
            var name = $('.'+id).find('a').text();
            var current_id = id.substring(4);
            var tr = '<tr>\n' +
                '<td></td>\n' +
                '<td><input type="hidden" value="'+current_id+'" name="id"><input type="hidden" value="'+name+'" name="attr-name"> '+name+' </td>\n' +
                '<td><input type="text" value="" name="attr-value"></td>\n' +
                '<td>\n' +
                '<span class="label label-warning deltr">删除</span>\n' +
                '<span class="label label-info save-attr-value">保存</span>\n' +
                '</td>\n' +
                '</tr>';
            table.append(tr);

            //保存属性值
            operation.saveAttrValue();
            operation.deleteAttrValue();
        });

    }
};

function Html(config){
    if(config.hasOwnProperty('appendLine')){
        this.appendLine = config.appendLine;
    }
}

Html.prototype = {
    constructor : Html,
    // 显示
    // 构建左边的.
    showNav:function (id,row) {
        $('.attribute-name').append([
            '<li class="',id,' "><a href="#',id,'" data-toggle="tab">',row.attribute_name,'</a></li>'
        ].join(''));
        // 先找到自己,添加active.并把兄弟节点删除active
        $('.' + id).addClass('active').siblings().removeClass('active');
    },
    // 构建右边表格.
    showTab:function(id,list) {
        var html = '<div class="tab-pane" id="'+id+'">'+ this.buildTab(list) +'</div>';
        //显示 属性列表
        $('.attribute-value').append(html);
        $('.attribute-value').find( '#'+id).addClass('active').siblings().removeClass('active');
        if(typeof this.appendLine == 'function')
        {
            this.appendLine();
        }
    },
    // 添加新行
    appendLine:function () {

    },
    //构建右边的表格
    buildTab:function(list){
        var trs = [];

        if(list.length > 0){
            for(var i =0,len = list.length;i<len;i++){
                trs.push([
                    '<tr data-id="',list[i].id,'" data-attr-name="',list[i].attr_name,'" data-attr-value="',list[i].value,'">',
                    '<td>',parseInt(i) + 1,'</td>',
                    '<td>',list[i].attr_name,'</td>',
                    '<td>',list[i].value,'</td>',
                    '<td>',
                    '<span class="label deltr label-warning">删除</span>',
                    '</td>',
                    '</tr>',
                ].join(''));
            }
        }

        return [
            '<div class="widget">',
            '     <div class="widget-body" style="padding:0;">',
            '         <table class="table table-bordered table-hover">',
            '             <thead>',
            '                <tr>',
            '                    <th>编号</th>',
            '                    <th>属性名称</th>',
            '                    <th>属性值</th>',
            '                    <th>操作 <span class="label label-success addtr">添加</span> </th>',
            '                </tr>',
            '             </thead>',
            '             <tbody>',
            trs.join(''),
            '             </tbody>',
            '         </table>',
            '     </div>',
            '</div>'
        ].join("");
    },
    // 渲染列表.
    display:function () {
        // 获取数据.
        var data = this.buildData();
        if(!data.hasOwnProperty("thead")){
            layer.msg('请添加属性和值');
            return false;
        }

        var thead = data.thead,
            rows = data.data;
        var th_html = [];
        // console.dir(thead);
        // console.dir(rows);

        for (var i = 0,len = thead.length;i<len;i++){
            th_html.push('<th class="width100">'+thead[i]+'</th>');
        }
        th_html.push('<th class="width100">原价</th><th class="width100">折扣价</th><th class="width100">单购价</th><th class="width100">库存</th><th class="width100">图片</th>');
        var trs_html = [];
        for(var i = 0,len = rows.length;i<len;i++){
            trs_html.push('<tr>');
            if(rows[i].attr_name1){
                trs_html.push('<td>'+rows[i].attr_name1+'</td>');
            }
            if(rows[i].attr_name2){
                trs_html.push('<td>'+rows[i].attr_name2+'</td>');
            }
            if(rows[i].attr_name3){
                trs_html.push('<td>'+rows[i].attr_name3+'</td>');
            }
            trs_html.push(
                '<td><input class="no_b need" type="text" name="original_price" placeholder="请输入" value=""></td>'+
                '<td><input class="no_b need" type="text" name="discount_price" placeholder="请输入" value=""></td>'+
                '<td><input class="no_b need" type="text" name="one_price" placeholder="请输入" value=""></td>'+
                '<td><input class="no_b need" type="text" placeholder="请输入" name="inventory[]" value=""></td>'+
                '<td width="160px;"><input class="no_b1 pic-card pic-card4" type="file" indexs="'+(i+1)+'"><input type="hidden" name="attrimgval" value="" class="attrimgvalue need  attrList imgindex'+(i+1)+'"></td>' +
                '<td style="display:none;"><input value="'+rows[i].attribute_value_id+'" class="need"/></td></tr>'
            );

        }
        var html = [
            '         <table class="table-bordered table-hover">',
            '             <thead class="thead">',
            '                <tr>',
            th_html.join(''),
            '                </tr>',
            '             </thead>',
            '             <tbody class="tbody">',
            trs_html.join(''),
            '             </tbody>',
            '         </table>'
        ].join("");
        $('.end-table').html(html);
        // console.dir(data);

    },
    // 生成数据.
    buildData:function () {
        var tbodies = $('.attribute-value').find('tbody');
        var data = [];
        for (var i =0,len=tbodies.length;i<len;i++){
            data.push(this.getAttrs($(tbodies[i])));
        }

        if(data.length == 0 || (!data[0].length && (data[1].length ? !data[1].length:0) && (data[2].length ?!data[2].length :0)))
        {
            return {};
        }
        var new_data = [],
            thead = [];
        data = data.filter(function(item){
            if(item.length > 0){
                return item;
            }
        });
        for(var i=0,len=data.length;i<len;i++)
        {
            if(data[i].length > 0)
            {
                thead.push(data[i][0].attr_name);
            }
        }

        var first = data.shift();
        first.map(function (item) {
            if(data.length >0 ){
                var second = data[0];
                second.map(function(list){
                    if(data.length>1){
                        var third = data[1];
                        for (var i=0,len=third.length;i<len;i++){
                            new_data.push({
                                'attribute_value_id':[item.id,list.id,third[i].id].join('-'),
                                'attr_name1':item.attr_value,
                                'attr_name2':list.attr_value,
                                'attr_name3':third[i].attr_value
                            });
                        }
                    }else{
                        new_data.push({
                            'attribute_value_id':[item.id,list.id,0].join('-'),
                            'attr_name1':item.attr_value,
                            'attr_name2':list.attr_value,
                            'attr_name3':''
                        });
                    }
                });
            }else{
                new_data.push({
                    'attribute_value_id':[item.id,0,0].join('-'),
                    'attr_name1':item.attr_value,
                    'attr_name2':'',
                    'attr_name3':''
                });
            }
        });

        return {
            'thead': thead,
            'data' : new_data
        };
    },
    getAttrs:function(tbody){
        var trs = tbody.find('tr');
        var data = [];
        for (var i=0,len=trs.length;i<len;i++){
            data.push({
                'id':trs[i].getAttribute('data-id'),
                'attr_name':trs[i].getAttribute('data-attr-name'),
                'attr_value':trs[i].getAttribute('data-attr-value')
            });
        }
        return data;
    }
};

$(function(){
    operation.init();
    $(".no_b").each(function(i){
        if(!$(".no_b").eq(i).val()){
            $(this).css('border','1px solid rgb(255,65,65)')
        }
    }).on('blur',function(){
        var val=$(this).val();
        if(!$(this).val()){
            $(this).css('border','1px solid rgb(255,65,65)')
        }else{
            $(this).css('border','none')                    
        }
    })
});